package com.zznode.redsun.smartcrm.business.service.impl;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;

import com.zznode.csp.domain.commons.persistence.EntityManager;
import com.zznode.csp.domain.commons.query.JdbcFinderManager;
import com.zznode.csp.domain.commons.query.Page;
import com.zznode.csp.domain.commons.util.MapCreaterBuilder;
import com.zznode.redsun.commons.dto.ProductDto;
import com.zznode.redsun.commons.dto.ProductQuery;
import com.zznode.redsun.commons.utils.GlobalUtils;
import com.zznode.redsun.smartcrm.business.service.ProductService;
import com.zznode.redsun.smartcrm.model.Product;
import com.zznode.redsun.smartcrm.model.Provider;

@Service
public class ProductServiceImpl implements ProductService {
	@Autowired
	private JdbcFinderManager jdbcFinderManager;
	@Autowired
	private EntityManager entityManager;

	@Override
	public void save(ProductDto dto) {
		if (null == dto) {
			return;
		}

		if (null == dto.getId()) {
			entityManager.save(dto.convert());
		} else {
			Product entity = entityManager.get(Product.class, dto.getId());
			dto.update(entity);
			entityManager.update(entity);
		}
	}

	@Override
	public ProductDto get(Long id) {
		if (null == id) {
			return null;
		}
		Product entity = entityManager.get(Product.class, id);
		return ProductDto.create(entity);
	}

	@Override
	public Page<ProductDto> query(ProductQuery params, int pageNumber, int pageSize) {
		String querySql = jdbcFinderManager.getQueryStringByStatementKey("ProductService_query");
		MapCreaterBuilder paramBuilder = MapCreaterBuilder.create();
		if (null != params) {
			querySql = params.buildSql(querySql, paramBuilder);
		}
		return jdbcFinderManager.queryForPage(querySql, paramBuilder.map(), new RowMapper<ProductDto>() {

			@Override
			public ProductDto mapRow(ResultSet rs, int arg1) throws SQLException {
				ProductDto dto = new ProductDto();
				dto.setId(rs.getLong("id"));
				dto.setCode(rs.getString("code"));
				dto.setName(rs.getString("name"));
				dto.setCreateDate(rs.getDate("create_date"));
				dto.setCreateDateString(GlobalUtils.formartDate(dto.getCreateDate()));
				dto.setProviderId(rs.getLong("provider_id"));
				dto.setProviderName(entityManager.get(Provider.class, dto.getProviderId()).getName());
				dto.setModel(rs.getString("model"));
				dto.setPrice(rs.getBigDecimal("price"));

				return dto;
			}
		}, pageNumber, pageSize);
	}
}
